package com.qf.openapi.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.qfsy.mqbean.ApiTimeCostMqBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

@Component
@Slf4j
public class TimeCostAfterFilter extends ZuulFilter {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        long start = (long) request.getAttribute("start");
        long end = System.currentTimeMillis();
        log.info("消耗的时间为:{}ms",(end-start));

        // 把接口执行时长信息封装成一个mqbean，写入mq中
        ApiTimeCostMqBean apiTimeCostMqBean = new ApiTimeCostMqBean();
        apiTimeCostMqBean.setApiName(request.getParameter("apiname"));
        apiTimeCostMqBean.setStart(new Date(start));
        apiTimeCostMqBean.setEnd(new Date(end));
        apiTimeCostMqBean.setTimecost((end-start));
        apiTimeCostMqBean.setRemoteIp(request.getRemoteAddr());
        apiTimeCostMqBean.setCustomerKey(request.getParameter("customerkey"));

        try {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            apiTimeCostMqBean.setServerIp(hostAddress);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        log.info("统计接口执行时长，信息封装到mqbean中，{}",apiTimeCostMqBean);

        String exchangename="openapi-timecost-exchange";
        String routingkye="openapi.timecost.apiTimeCostMqBean";
        rabbitTemplate.convertAndSend(exchangename,routingkye,apiTimeCostMqBean);

        return null;
    }
}
